package com.algorithm.lesson_05;

import java.util.LinkedList;

public class DogCatQueueImpl implements DogCatQueue {

	private LinkedList<PetEnterQueue> dogQueue;
	private LinkedList<PetEnterQueue> catQueue;
	private int count = 0;// 时间戳

	public DogCatQueueImpl() {
		dogQueue = new LinkedList<>();
		catQueue = new LinkedList<>();
	}

	@Override
	public void add(Pet pet) {
		if (pet.getPetType().equals(Pet.TYPE_DOG)) {
			dogQueue.addLast(new PetEnterQueue(pet, count++));
		} else if (pet.getPetType().equals(Pet.TYPE_CAT)) {
			catQueue.addLast(new PetEnterQueue(pet, count++));
		} else {
			throw new RuntimeException("Pet Type Error!");
		}
	}

	@Override
	public Pet pollAll() {
		if (!isDogEmpty() && !isCatEmpty()) {
			// 狗队列和猫队列都非空，分别取出最早的狗和猫进行时间戳的比较
			PetEnterQueue dog = dogQueue.peekFirst();
			PetEnterQueue cat = catQueue.peekFirst();
			Pet pet = dog.getCount() < cat.getCount() ? dogQueue.pollFirst().getPet() : catQueue.pollFirst().getPet();
			return pet;
		} else if (!isDogEmpty()) {
			// 狗队列非空，猫队列为空
			return dogQueue.pollFirst().getPet();
		} else if (!isCatEmpty()) {
			// 猫队列非空，狗队列为空
			return catQueue.pollFirst().getPet();
		} else {
			// 狗队列和猫队列都为空
			throw new RuntimeException("Queue is Empty!");
		}
	}

	@Override
	public Dog pollDog() {
		if (isDogEmpty()) {
			throw new RuntimeException("Dog Queue is Empty!");
		} else {
			return (Dog) dogQueue.pollFirst().getPet();
		}
	}

	@Override
	public Cat pollCat() {
		if (isCatEmpty()) {
			throw new RuntimeException("Cat Queue is Empty!");
		} else {
			return (Cat) catQueue.pollFirst().getPet();
		}
	}

	@Override
	public boolean isEmpty() {
		return isDogEmpty() && isCatEmpty();
	}

	@Override
	public boolean isDogEmpty() {
		return dogQueue.isEmpty();
	}

	@Override
	public boolean isCatEmpty() {
		return catQueue.isEmpty();
	}

}
